package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.PageDto;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * 角色管理
 */
@RestController
@Slf4j
@RequestMapping("sys_role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @GetMapping("/allData")
    public ResultData allData() {
        List<Role> list = roleService.list();
        return ResultData.ok("", list);
    }

    @GetMapping("/list")
    public ResultData list(String name, int page, int limit) {
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(StringUtils.isNotEmpty(name), Role::getName, name);

        Page<Role> rolePage = new Page<>(page, limit);

        Page<Role> page1 = roleService.page(rolePage, roleLambdaQueryWrapper);

        PageDto pageDto = PageUtils.getPageDto(page1);


        return ResultData.ok("", pageDto);
    }

    @GetMapping("/rowInfo")
    public ResultData rowInfo(@RequestParam String id) {
        log.info("id为:{}", id);

        Role byId = roleService.getById(id);

        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RoleMenu::getRole_id, byId.getId());
        List<RoleMenu> list = roleMenuService.list(queryWrapper);



        for (int i = 0; i < list.size(); i++) {
            String role_id = list.get(i).getRole_id();
            byId.setRole_id(role_id);
            byId.setMenu_id(list.get(i).getMenu_id());
        }
        System.out.println(byId.toString());
        return ResultData.ok("", byId);
    }

    @GetMapping("/del")
    public ResultData del(@RequestParam String id) {
        roleService.removeRMM(id);
        return ResultData.ok("", "");
    }

    @PostMapping("/add")
    public ResultData add(@RequestBody Role role) {
        log.info(role.toString());
        role.setId(DigestUtils.md5Hex(UUID.randomUUID().toString()));
        role.setDefault_data("1");
        roleService.save(role);
        return ResultData.ok("1", "成功");
    }
}
